from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import InvalidToken, AuthenticationFailed
from rest_framework_simplejwt.tokens import RefreshToken as OriginalRefreshToken
from .models import User
import logging

logger = logging.getLogger(__name__)

class RefreshToken(OriginalRefreshToken):
    """自定义的RefreshToken类以支持我们的User模型"""
    
    @classmethod
    def for_user(cls, user):
        """
        为指定用户返回RefreshToken
        """
        token = cls()
        token['user_id'] = user.id
        token['username'] = user.username
        token['role'] = user.role
        
        logger.debug(f"Created token for user: {user.username} with ID: {user.id}")
        return token

class CustomJWTAuthentication(JWTAuthentication):
    """
    自定义JWT认证类以支持我们的User模型
    """
    def authenticate(self, request):
        """
        重写authenticate方法以添加更多日志
        """
        logger.info("开始JWT身份验证")
        
        # 获取请求头中的Authorization内容
        header = self.get_header(request)
        if header is None:
            logger.warning("请求头中没有Authorization")
            return None
        
        # 获取原始token
        raw_token = self.get_raw_token(header)
        if raw_token is None:
            logger.warning("无法从请求头中提取原始token")
            return None
        
        logger.info(f"从请求头中获取到原始token: {raw_token[:10]}...")
        
        # 验证token
        try:
            validated_token = self.get_validated_token(raw_token)
            logger.info(f"成功验证token，token内容: {validated_token}")
        except Exception as e:
            logger.error(f"验证token时出错: {str(e)}")
            raise
        
        # 获取用户
        try:
            user = self.get_user(validated_token)
            logger.info(f"成功获取用户: {user.username if user else None}")
            return (user, validated_token)
        except Exception as e:
            logger.error(f"获取用户时出错: {str(e)}")
            raise
            
    def get_user(self, validated_token):
        """
        根据验证过的token获取用户
        """
        try:
            user_id = validated_token['user_id']
            
            # 记录获取用户的过程
            logger.debug(f"尝试获取ID为 {user_id} 的用户")
            
            try:
                user = User.objects.get(id=user_id)
                logger.debug(f"找到用户: {user.username}")
                return user
            except User.DoesNotExist:
                logger.warning(f"未找到ID为 {user_id} 的用户")
                # 显示所有用户ID，用于调试
                try:
                    all_user_ids = list(User.objects.values_list('id', flat=True))
                    logger.warning(f"数据库中的用户ID: {all_user_ids}")
                except Exception as e:
                    logger.error(f"获取所有用户ID时出错: {str(e)}")
                raise AuthenticationFailed('未找到匹配此token的用户')
        except KeyError:
            logger.error("Token载荷中不包含user_id")
            raise InvalidToken('Token中不包含可识别的用户标识')
        except Exception as e:
            logger.error(f"身份验证出错: {str(e)}")
            raise AuthenticationFailed('身份验证过程中出错') 